import { createRequire } from 'node:module';

import { APP_PATH } from '../../utils/index.mjs';

const require = createRequire(import.meta.url);
const fs = require('node:fs');
const path = require('node:path');

export function createAppHandler(app, logger) {
  // =================设计保存、查询 Begin============================
  // 获取设计映射文件
  app.get('/app/list', (req, res) => {
    const customPath = path.resolve(APP_PATH, `custom.json`);
    const systemPath = path.resolve(APP_PATH, `system.json`);
    try {
      let custom = '[]';
      let system = '[]';
      if (fs.existsSync(customPath)) {
        custom = fs.readFileSync(customPath, 'utf8');
      }
      if (fs.existsSync(systemPath)) {
        system = fs.readFileSync(systemPath, 'utf8');
      }

      res.send({
        code: 200,
        data: { custom: JSON.parse(custom), system: JSON.parse(system) },
        msg: 'custom.json 存在',
      });
    } catch (error) {
      logger.error(error);
      res.send({
        code: 500,
        data: { custom: [], system: [] },
        msg: 'custom.json 不存在',
      });
    } finally {
      res.end();
    }
  });

  // 删除映射文件
  app.delete('/app/delete/:id', async (req, res) => {
    const id = req.params.id;
    const type = req.query.type;
    if (!id) {
      res.send({ code: 500, msg: '参数错误' });
      return;
    }

    try {
      let filePath = path.resolve(APP_PATH, `custom.json`);
      if (type === 'system') {
        filePath = path.resolve(APP_PATH, `system.json`);
      } else if (type === 'custom') {
        filePath = path.resolve(APP_PATH, `custom.json`);
      }

      if (fs.existsSync(filePath)) {
        let appData = JSON.parse(fs.readFileSync(filePath, 'utf8'));
        appData = appData.filter((item) => item.key !== id);

        fs.writeFileSync(filePath, JSON.stringify(appData));
      }
      res.send({ code: 200, msg: '删除成功' });
    } catch (error) {
      logger.error(error);
      res.send({ code: 500, msg: '文件不存在' });
    } finally {
      res.end();
    }
  });

  // 保存app文件
  app.post('/app/save/:id', (req, res) => {
    const id = req.params.id;
    if (!id) {
      res.send({ code: 500, msg: '参数错误' });
      return;
    }
    let data = '';
    req.on('data', (chunk) => {
      data += chunk;
    });
    req.on('end', async () => {
      try {
        data = JSON.parse(data); // 将JSON字符串解析成对象
        let filePath = path.resolve(APP_PATH, `custom.json`);
        if (data.type === 'system') {
          filePath = path.resolve(APP_PATH, `system.json`);
        } else if (data.type === 'custom') {
          filePath = path.resolve(APP_PATH, `custom.json`);
        }
        let appData = [];
        if (fs.existsSync(filePath)) {
          appData = JSON.parse(fs.readFileSync(filePath, 'utf8'));
          const app = appData.find((item) => item.key === data.key);
          if (app) {
            Object.assign(app, data);
          } else {
            appData.push(data);
          }
        } else {
          appData.push(data);
        }

        fs.writeFileSync(filePath, JSON.stringify(appData));
        res.send({ code: 200, msg: '保存成功' });
      } catch (error) {
        logger.info(error);
        res.send({ code: 500, msg: '保存失败' });
      } finally {
        res.end();
      }
    });
  });

  // 保存app文件
  app.post('/app/savedefault', (req, res) => {
    let data = '';
    req.on('data', (chunk) => {
      data += chunk;
    });
    req.on('end', async () => {
      try {
        const systemPath = path.resolve(APP_PATH, `system.json`);
        fs.writeFileSync(systemPath, data);
        res.send({ code: 200, msg: '保存成功' });
      } catch (error) {
        logger.info(error);
        res.send({ code: 500, msg: '保存失败' });
      } finally {
        res.end();
      }
    });
  });
  // =================设计保存、查询 End============================
}
